// app/service/user.js
const Service = require('egg').Service
const { Op } = require('sequelize')
class BaseService extends Service {
	async listAll(options) {
		return await this.ctx.model[this.modelName].findAll(options)
	}
	async list(options) {
		return await this.ctx.model[this.modelName].findAndCountAll(options)
	}

	async findLike(options) {
		return await this.ctx.model[this.modelName].findAndCountAll(options)
	}
	async add(body, where) {
		// 添加之前做判断
		const old = await this.ctx.model[this.modelName].findOne({ ...where })
		if (old) return { flag: false, msg: '数据已经存在了', code: 400 }
		let data = await this.ctx.model[this.modelName].create(body)
		if (data) {
			return { flag: true, data }
		} else {
			return { flag: false, msg: '数据添加错误', code: 400 }
		}
	}
	async del(ids) {
		if (!Array.isArray(ids)) ids = [ids]
		let transaction

		try {
			// 建立事务对象
			transaction = await this.ctx.model.transaction()
			for (let i = 0; i < ids.length; i++) {
				const id = ids[i]
				let res = await this.ctx.model[this.modelName].destroy({
					where: {
						id: {
							[Op.eq]: id,
						},
					},
					transaction,
				})
				if (!res) {
					throw error //数据不存在就回滚
				}
			}
			// 提交事务
			await transaction.commit()
			return { flag: true }
		} catch (error) {
			// 事务回滚
			await transaction.rollback()
			return { flag: false, msg: '数据不存在', code: 400 }
		}
	}
	async update(obj) {
		return await this.ctx.model[this.modelName].update(
			{ ...obj },
			{
				where: {
					id: {
						[Op.eq]: obj.id,
					},
				},
			}
		)
	}
	async updateList(arr) {
		return await this.ctx.model[this.modelName].bulkCreate(arr, {
			updateOnDuplicate: ['name'],
		})
	}
}

module.exports = BaseService
